<?php

use think\Db;
use think\Session;
use \itbdw\Ip\IpLocation;
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件

//管理员日志
function adminlog($cname = '登陆成功', $ctype = '登陆', $text = '')
{
	$id = Session::get('user_id');
	if (empty($id)) {
		$log['last_login_ip'] = 0;
		$log['last_login_time'] = 0;
		$log['addtime'] = time();
		$log['loginnum'] = 0;
		$log['admin_id'] = 0;
		$log['cname'] = $cname;
		$log['ctype'] = $ctype;
		$log['text'] = $text;
	} else {
		$adminlog = Db::name('admin')->find($id);
		$log['last_login_ip'] = $adminlog['last_login_ip'];
		$log['last_login_time'] = $adminlog['last_login_time'];
		$log['addtime'] = time();
		$log['loginnum'] = $adminlog['loginnum'];
		$log['admin_id'] = $adminlog['id'];
		$log['cname'] = $cname;
		$log['ctype'] = $ctype;
		$log['text'] = $text;
	}

	Db::name('admin_log')->insert($log);
}

//生成保修卡编号
function bh()
{
	$yCode  = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
	$result = 'HB' . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) .  $yCode[intval(rand(0, 25))] . sprintf('%02d', rand(80, 99));
	return $result;
}


//判断是否是多序列号
//status 0 单序列号 1多序列号
//key 传入的sn
//sn 另一个sn
function more_sn($sn)
{
	//$sn="sn_999884";
	$info = Db::name('tagslogs')->where('sn', $sn)->find();
	if (!empty($info)) {
		$infoa = Db::name('more_sn')->where('key', 'like', '%' . $sn . '%')->find();
		if (!empty($infoa)) {
			$arr = strtoarr($infoa['key']);
			if (in_array($sn, $arr)) {
				$bk_arr=$arr;
				$str = '';
				foreach ($arr as $k => $v) {
					if ($sn == $v) {
						unset($arr[$k]);
					}
				}
				$str = implode(",", $arr); //数组转字符串
				//halt($arr);
				return ['status' => 1, 'key' => $sn, 'sn' => $str,'one'=>$bk_arr[0],'id'=>$infoa['id']];
			} else {
				return ['status' => 0, 'key' => $sn, 'sn' => [],'one'=>'','id'=>0];
			}
		} else {
			return ['status' => 0, 'key' => $sn, 'sn' => [],'one'=>'','id'=>0];
		}
	} else {
		return ['status' => 0, 'key' => $sn, 'sn' => [],'one'=>'','id'=>0];
	}
}
//多序列号的列表只显示一条数据
//list数据和
//str查询字段
function more_sn_one($list,$str){
	if(empty($list)){
		return [];
	}
	foreach ($list as $key1 => $val1) {
		if (!empty($val1[$str])) {
			$more_sn=more_sn($val1[$str]);
			if($more_sn['status']==1){
				if($val1[$str]!=$more_sn['one']){
					unset($list[$key1]);
				}
			}
		}	
	}
	return $list;

}

//二维数组转一维数组
function array_to_arr($array, $id)
{
	$arr = array();
	foreach ($array as $key => $val) {
		array_push($arr, $val[$id]);
	}
	return $arr;
}

//根据ip地址获取位置
function getlocation($ip)
{
	return IpLocation::getLocation($ip);
}

// 根据sn获取企业信息
function getcompany($sn)
{
	$status = 0;
	$msg = '公司不存在';
	$data = [];

	$tagslogs = Db::name('tagslogs')->where('sn', $sn)->find();
	if ($tagslogs) {
		$goodstags = Db::name('goodstags')->where('id', $tagslogs['goodstags_id'])->find();
		if ($goodstags) {
			$good = Db::name('good')->where('id', $goodstags['good_id'])->find();
			if ($good) {
				$series = Db::name('series')->where('id', $good['series'])->find();
				if ($series) {
					$brand = Db::name('brand')->where('id', $series['brand_id'])->find();
					if ($brand) {
						$company = Db::name('company')->where('id', $brand['company_id'])->find();
						$status = 1;
						$msg = '查询成功';
						$data = $company;
					}
				}
			}
		}
	}

	return ['status' => $status, 'msg' => $msg, 'data' => $data];
}

//字符串转数组
function strtoarr($data)
{
	// $find     = array("\r\n", "\r", "\n", ",,"," ","，");
	$find     = array(",,", "，");
	$replace  = array(",");
	$temp_str = str_replace($find, ',', $data);
	//dump($temp_str);exit();
	$arr   = explode(",", $temp_str);
	return $arr;
}
//判断是否包含某个字符
function checkstr($str, $key)
{ //$str字符串，$key被包含的字符
	$tmparray = explode($key, $str);
	if (count($tmparray) > 1) {
		return true;
	} else {
		return false;
	}
}

//查找sn
function is_sn($sn)
{
	$info = Db::name('tagslogs')->where('sn', $sn)->find();
	if (empty($info)) {

		$infoa = Db::name('tagslogs')->where('sn', 'like', '%' . $sn . '%')->where('sn', 'like', '%,%')->find();
		if (empty($infoa)) {
			$infoa = Db::name('tagslogs')->where('sn', 'like', '%' . $sn . '%')->where('sn', 'like', '%，%')->find();
			if (empty($infoa)) {
				return ['status' => 0, 'key' => $sn, 'sn' => []];
			} else {
				return ['status' => 1, 'key' => $sn, 'sn' => $infoa['sn']];
			}
		} else {
			return ['status' => 1, 'key' => $sn, 'sn' => $infoa['sn']];
		}
	} else {
		return ['status' => 1, 'key' => $sn, 'sn' => $info['sn']];
	}
}

//获取短信通知模板
function get_msg_temp($id){
	$res=Db::name('api_message_temp')->where('id',$id)->find();
	return $res;
}
//手机短信接口
/**
 * @param type 默认yzm：验证码，shenhe：保修审核，jihuo：保修激活
 */
function send_mobile_message($telephone, $type = "yzm", $sn= '')
{
	if(empty($sn)){
		return ['status' => 0, 'msg' => '参数错误'];
	}else{
		$d=getcompany($sn);
		if($d['status']==1){
			$company=$d['data'];
			import("ChuanglanSmsApi.php");
			$clapi  = new ChuanglanSmsApi($company['api_name'],$company['api_pass']);
		}else{
			return ['status' => 0, 'msg' => '参数错误'];
		}
	}
	
	
	$code = mt_rand(1000, 9999);
	//设置您要发送的内容：其中“【】”中括号为运营商签名符号，多签名内容前置添加提交
	// $result = $clapi->sendSMS(trim($telephone), "【二校门】亲爱的用户您好，您的验证码为" . $code . "，此操作5分钟内有效，请尽快完成验证.本短信不用回复！");
	switch ($type) {
		case 'yzm':
			//$result = $clapi->sendSMS(trim($telephone), "【315云防伪】亲爱的用户，" . $code . "为您的验证码，此操作5分钟内有效，请尽快完成验证.本短信不用回复");
			$result = $clapi->sendSMS(trim($telephone), $company['smstitle']."亲爱的用户，" . $code . "为您的验证码，此操作5分钟内有效，请尽快完成验证.本短信不用回复");
			break;
		case 'shenhe':
			$notice=Db::name('api_message_temp')->where('id',1)->value('content');
			//$result = $clapi->sendSMS(trim($telephone), "【315云防伪】亲爱的用户，您的设备保修激活申请已提交，等待审核中.本短信不用回复");
			$result = $clapi->sendSMS(trim($telephone),  $company['smstitle'].$notice);
			break;
		case 'jihuo':
			// $result = $clapi->sendSMS(trim($telephone), "【315云防伪】亲爱的用户，您的设备保修卡已激活.本短信不用回复");
			$notice=Db::name('api_message_temp')->where('id',3)->value('content');
			// 查询保修期限
			$card = Db::name('card')->where('tagslogs_sn',$sn)->find();
			$card['starttime'] = date('Y-m-d H:i:s', $card['starttime']);
			$card['endtime'] = date('Y-m-d H:i:s', $card['endtime']);
			$result = $clapi->sendSMS(trim($telephone),$company['smstitle'].$notice.'，保修期限为：'.$card['starttime'].'至'.$card['endtime'].'.本短信不用回复');
			break;
		case 'jujue':
			$notice=Db::name('api_message_temp')->where('id',4)->value('content');
			// $result = $clapi->sendSMS(trim($telephone), "【315云防伪】亲爱的用户，您的设备保修卡审核不通，详情请联系客服人员.本短信不用回复");
			$result = $clapi->sendSMS(trim($telephone), $company['smstitle'].$notice);
		case 'kfmsg':
			//$result = $clapi->sendSMS(trim($telephone), "【315云防伪】亲爱的用户，您有设备保修激活申请需要审核，详情请登录系统查看.本短信不用回复");
			$notice=Db::name('api_message_temp')->where('id',2)->value('content');
			$result = $clapi->sendSMS(trim($telephone), $company['smstitle'].$notice);
			break;
		case 'shpass':
			$notice=Db::name('api_message_temp')->where('id',5)->value('content');
			// $result = $clapi->sendSMS(trim($telephone), "【315云防伪】亲爱的用户，您的设备维修审核已通过，详情请扫码登录系统查看.本短信不用回复");
			$result = $clapi->sendSMS(trim($telephone), $company['smstitle'].$notice);
			break;
		case 'useraddfix':
			// 添加维修通知
			$notice=Db::name('api_message_temp')->where('id',6)->value('content');
			// $result = $clapi->sendSMS(trim($telephone), "【315云防伪】亲爱的用户，您的设备维修审核已通过，详情请扫码登录系统查看.本短信不用回复");
			$result = $clapi->sendSMS(trim($telephone), $company['smstitle'].$notice);
			break;
		case 'kfaddfix':
			// 添加维修通知
			$notice=Db::name('api_message_temp')->where('id',7)->value('content');
			// $result = $clapi->sendSMS(trim($telephone), "【315云防伪】亲爱的用户，您的设备维修审核已通过，详情请扫码登录系统查看.本短信不用回复");
			$result = $clapi->sendSMS(trim($telephone), $company['smstitle'].$notice);
			break;
		default:
			break;
	}

	if (!is_null(json_decode($result))) {

		$output = json_decode($result, true);

		if (isset($output['code'])  && $output['code'] == '0') {
			// echo '发送成功';
			Session::set('sh_message', $code);
			return ['status' => 1, 'msg' => '发送成功'];
		} else {
			// echo $output['errorMsg'];
			return ['status' => 0, 'msg' => $output['errorMsg']];
		}
	} else {

		return ['status' => 0, 'msg' => $result];
	}
}

// 公共发送邮件的方法
function sendToMail($to, $title, $content)
{
	require_once './PHPMailer/PHPMailerAutoload.php';
	
	$mail = new \PHPMailer(); //实例化
	//使用smtp鉴权方式发送邮件
	$mail->isSMTP();
	//smtp需要鉴权 这个必须是true
	$mail->SMTPAuth = true;
	// qq 邮箱的 smtp服务器地址，这里当然也可以写其他的 smtp服务器地址
	//$mail->Host = 'smtp.qq.com';
	$mail->Host = 'smtp.qiye.163.com';
	//smtp登录的账号 这里填入字符串格式的qq号即可
	$mail->Username = config('email.name');
	// 这个就是之前得到的授权码，一共16位
	$mail->Password = config('email.code');;
	$mail->setFrom(config('email.name'));
	// $to 为收件人的邮箱地址，如果想一次性发送向多个邮箱地址，则只需要将下面这个方法多次调用即可
	if (is_array($to)) {
		foreach ($to as $key => $value) {
			$mail->addAddress($value);
		}
	} else {
		$mail->addAddress($to);
	}
	// 该邮件的主题
	$mail->Subject = $title;
	// 该邮件的正文内容
	$mail->Body = $content;

	$mail->SMTPSecure = 'ssl';
	// 设置ssl连接smtp服务器的远程服务器端口号
	$mail->Port = 465;
	// 使用 send() 方法发送邮件
	if (!$mail->send()) {
		return false;
		//return '发送失败: ' . $mail->ErrorInfo;
	} else {
		return true;
		//return "发送成功";
	}
}

// 公共发送邮件的方法
// function sendToMailwx($to, $title, $content)
// {
// 	require_once './PHPMailer/PHPMailerAutoload.php';
	
// 	$mail = new \PHPMailer(); //实例化
	   
//         $mail->IsSMTP(); // 启用SMTP
//         $mail->Host='smtp.163.com'; //smtp服务器的名称（这里以QQ邮箱为例）
//         $mail->SMTPAuth = TRUE; //启用smtp认证
//         $mail->Username = C('MAIL_USERNAME'); //你的邮箱名
//         $mail->Password = C('MAIL_PASSWORD') ; //邮箱授权码
//         $mail->From = C('MAIL_FROM'); //发件人地址（也就是你的邮箱地址）
//         $mail->FromName = C('MAIL_FROMNAME'); //发件人姓名
//         $mail->AddAddress($to,"尊敬的客户");
//         $mail->WordWrap = 50; //设置每行字符长度
//         $mail->IsHTML(C('MAIL_ISHTML')); // 是否HTML格式邮件
//         $mail->CharSet=C('MAIL_CHARSET'); //设置邮件编码
//         $mail->Subject =$title; //邮件主题
//         $mail->Body = $content; //邮件内容
//         $mail->AltBody = "这是一个纯文本的身体在非营利的HTML电子邮件客户端"; //邮件正文不支持HTML的备用显示
//         return($mail->Send());
// 	// 使用 send() 方法发送邮件
// 	if (!$mail->send()) {
// 		return false;
// 		//return '发送失败: ' . $mail->ErrorInfo;
// 	} else {
// 		return true;
// 		//return "发送成功";
// 	}
// }
